package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.RecommendUserDto;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TodayBestService {
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @DubboReference
    private UserInfoApi userInfoApi;

    public TodayBest todayBest() {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用RecommendUserApi查询推荐数据  RecommendUser(userId,toUserId,Score)
        RecommendUser user = recommendUserApi.queryWithMaxScore(userId);
        //3、根据推荐用户ID，查询用户资料  UserInfo
        UserInfo userInfo = userInfoApi.findById(user.getUserId());
        //4、接收在实体类内创建init()将UserInfo转化为TodayBest对象
        TodayBest init = TodayBest.init(userInfo, user);
        //5、返回
        return init;
    }

    //查询推荐的今日佳人分页列表
    public PageResult recommendation(RecommendUserDto dto) {
        //1、获取参数 （当前用户id，page，pagesize）
        Long userId = UserHolder.getUserId();
        //2、调用recommendUserApi分页查询推荐用户列表 PageResult<RecommendUser列表>
        PageResult pr = recommendUserApi.queryRecommendUserList(userId, dto.getPage(), dto.getPagesize());
        //3、获取分页的数据列表 ： RecommendUser列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        if (CollUtil.isEmpty(items)) {
            return pr;
        }
        //4、一个RecommendUser封装成一个TodayBest对象
        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo userInfo = userInfoApi.findById(item.getUserId());
            TodayBest vo = TodayBest.init(userInfo, item);
            vos.add(vo);
        }
        //5、返回
        pr.setItems(vos); //替换pageresult中的items列表（recommendUser -- todayBest）
        return pr;
    }
}
